﻿//using ET.DBCommon.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
//using ET.DBCommon.Model;
using System.Collections.ObjectModel;
using Newtonsoft.Json;
using System.Data;
using Newtonsoft.Json.Linq;
//using ET.DBCommon.Enum;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Web.Script.Serialization;
using System.Drawing.Drawing2D;
using ET_DbCommon.Model;
using ET_DbCommon.Enum;
using ET_DbCommon.DAL;
using DirectShowLib;
using System.Configuration;

namespace ET.ScoreTeacherClient.Views
{
    /// <summary>
    /// TestQuestionTaskStepEdit.xaml 的交互逻辑
    /// </summary>
    public partial class TestQuestionTaskStepEdit : Window, INotifyPropertyChanged
    {
        public TestQuestionTaskStepViewModel viewModel { get; set; }
        public TestQuestionViewModel viewModelQuestion { get; set; }
        public List<postModel> roleModels { get; set; } = PostDAL.GetPostInfo();
        public ObservableCollection<PublicParameter> DevStateList { get; set; } = new ObservableCollection<PublicParameter>();
        public ObservableCollection<TrainPositionParameter> TrainPositionList { get; set; } = new ObservableCollection<TrainPositionParameter>();
        public ObservableCollection<BeforeStepParameter> BeforeList { get; set; } = new ObservableCollection<BeforeStepParameter>();
        public ObservableCollection<IntervalMonitorParameter> IntervalMonitorList { get; set; } = new ObservableCollection<IntervalMonitorParameter>();

        #region DicDevType
        #region DicDevType
        private Dictionary<int, string> m_DicDevType;

        public Dictionary<int, string> DicDevType
        {
            get
            {
                return this.m_DicDevType;
            }
            set
            {
                this.m_DicDevType = value;
                this.OnPropertyChanged();
            }
        }
        private Dictionary<int, string> m_DicDevType1;

        public Dictionary<int, string> DicDevType1
        {
            get
            {
                return this.m_DicDevType1;
            }
            set
            {
                this.m_DicDevType1 = value;
                this.OnPropertyChanged();
            }
        }
        #endregion
        #endregion


        public List<DeviceModel> TrainList { get; set; } = MainWindowNew.DeviceList[(int)DeviceTypeEnum.列车];
        public List<DeviceModel> AreaList { get; set; } = MainWindowNew.DeviceList[(int)DeviceTypeEnum.计轴区段];
        public List<DeviceModel> MyAreaList { get; set; } = MainWindowNew.DeviceList[(int)DeviceTypeEnum.计轴区段];
        public List<DeviceModel> MyStation { get; set; } = MainWindowNew.DeviceList[(int)DeviceTypeEnum.车站];//获取所有车站 Modify by lukun

        public List<DirectionClass> MyDirection { get; set; } = new List<DirectionClass>();
        public List<Paper_TestQuestion_Task_StepModel> BeforeStepList { get; set; }
        public List<OperateItemModel> StepItemList = OperateItemDAL.GetOperateItems();
        public bool IsSelected = false;//指示是否启动筛选功能
        Task select;
        ListenToFuzzyQueryVoid fuzzyQuery;//步骤筛选类
        CancellationTokenSource tokenSource;
        CancellationToken cancellationToken;//取消筛选步骤线程
        List<TestQuestionTaskStepViewModel> tempStepList = TestPaper.TestQuestionTaskStepList;
        #region INotifyPropertyChanged 接口实现
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged([CallerMemberName] string propName = null)
        {
            this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
        }
        #endregion

        public bool IsLook { get; set; }
        public TestQuestionTaskStepEdit(TestQuestionTaskStepViewModel _viewModel, TestQuestionViewModel _viewModelQuestion, bool _isLook = false)
        {
            InitializeComponent();
            this.viewModel = _viewModel;
            this.viewModelQuestion = _viewModelQuestion;
            this.IsLook = _isLook;
        }
       

        /// <summary>
        /// 保存步骤
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            #region
            PrerequisiteJson prerequisiteJson = new PrerequisiteJson();
            //列车位置
            Dictionary<string, bool> dicTrainPosition = new Dictionary<string, bool>();
            foreach (var param in this.TrainPositionList)
            {
                TrainLocation trainLocation = new TrainLocation();
                trainLocation.DevTrainID = param.DevTrainID;
                trainLocation.DevTrainName = param.DevTrainName;
                trainLocation.DevAreaID = param.DevAreaID;
                trainLocation.DevAreaName = param.DevAreaName;
                trainLocation.StationID = param.StationID;
                trainLocation.StationName = param.StationName;
                trainLocation.IsStop = param.IsStop;
                prerequisiteJson.trainPositions.Add(trainLocation);
            }

            //事前步骤
            Dictionary<int, int> dicBefore = new Dictionary<int, int>();
            foreach (var param in this.BeforeList)
            {
                if (param.StepID == 0) continue;
                AdvanceSteps advanceSteps = new AdvanceSteps();
                advanceSteps.StepID = param.StepID;
                advanceSteps.Delay = param.Delay;
                prerequisiteJson.beforeSteps.Add(advanceSteps);
            }
            //设备状态
            Dictionary<string, int> dic = new Dictionary<string, int>();
            foreach (var param in this.DevStateList)
            {
                var deviceStateList = MainWindowNew.DeviceStateList[param.DevType];
                var deviceStateModel = deviceStateList.FirstOrDefault(x => x.DeviceStatus == param.DevStateName);
                var deviceList = MainWindowNew.DeviceList[param.DevType];
                var device = deviceList.First(x => x.DeviceName == param.DevName);
                DeviceStatus deviceStatus = new DeviceStatus();
                deviceStatus.DevID = device.DeviceId;
                deviceStatus.DevName = param.DevName;
                deviceStatus.DevStateID = deviceStateModel == null ? 0 : deviceStateModel.Id;
                deviceStatus.DevStateName = param.DevStateName;
                deviceStatus.DevType = param.DevType;
                deviceStatus.DevTypeName = param.DevTypeName;
                prerequisiteJson.parameters.Add(deviceStatus);
            }
            //区间检测
            Dictionary<string, bool> dicIM = new Dictionary<string, bool>();
            foreach(var param in this.IntervalMonitorList)
            {
                if (param.StartStationID==0 || param.EndStationID == 0) continue;
                //  dicIM.Add(param.StartStationID + "|"+param.EndStationID+"|"+param.Direction,param.IsTrainON);
                IntervalDetection intervalDetection = new IntervalDetection();
                prerequisiteJson.intervalMonitors.Add(intervalDetection);
            }
            if (prerequisiteJson.beforeSteps.Count==0&& prerequisiteJson.intervalMonitors.Count == 0 
                && prerequisiteJson.parameters.Count == 0 && prerequisiteJson.trainPositions.Count == 0)
            {
                viewModel.Prerequisite =null;
            }
            else
            {
                //转成Json
                viewModel.Prerequisite = JsonConvert.SerializeObject(prerequisiteJson);
            }
            #endregion
            if (!string.IsNullOrWhiteSpace(cmbRole.Text))
            {
                List<string> roleIDStrings = new List<string>();
                var roleNames = cmbRole.Text.Split(',').ToList();
                foreach (var roleName in roleNames)
                {
                    string roleID = roleModels.FirstOrDefault(t => t.post_name == roleName).post_id;
                    roleIDStrings.Add(roleID);
                }
                viewModel.RoleId = string.Join(",", roleIDStrings);
            }
            if (!string.IsNullOrWhiteSpace(cmbDevice.Text))
            {

                //StringBuilder sb = new StringBuilder();

                //foreach (var item in cmbDevice.Text.Split(','))
                //{
                //    if (!int.TryParse(item, out int num) || item == "119" || item == "120" || item == "110" || item == "0")
                //    {
                //        List<DeviceModel> devs = new List<DeviceModel>();
                //        if (viewModel.DeviceTypeId != 0)
                //            devs.AddRange(MainWindowNew.DeviceList[viewModel.DeviceTypeId]);

                //        sb.Append(devs.FirstOrDefault(t => t.DeviceName == item).DeviceId).Append(",");
                //    }
                //    else
                //    {
                //        sb.Append(item).Append(",");
                //    }

                //}
                //viewModel.DeviceId = sb.ToString().TrimEnd(',');


                var idList = new List<int>();
                foreach (var item in cmbDevice.SelectedItems)
                {
                    if (item is DeviceModel deviceModel)
                    {
                        idList.Add(deviceModel.DeviceId);
                    }
                }
                viewModel.DeviceId = string.Join(",", idList);
            }


            if (viewModel.Id == 0)
            {
                int newId = Paper_TestQuestion_Task_StepDAL.Insert(viewModel.Model);
                if (newId > 0)
                {
                    viewModel.Id = newId;
                    this.DialogResult = true;
                }
            }
            else
            {
                Paper_TestQuestion_Task_StepDAL.Update(viewModel.Model);
                this.DialogResult = true;
            }

        }

        private void BtnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
        
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            tokenSource = new CancellationTokenSource();
            fuzzyQuery = new ListenToFuzzyQueryVoid();
            cancellationToken =  tokenSource.Token;
            fuzzyQuery.OnFuzzyQuery += UpdateQueryResult;
            #region 事前步骤
            if (!string.IsNullOrWhiteSpace(this.viewModel.Prerequisite)) 
            {
                 PrerequisiteJson  prerequisiteJson = JsonConvert.DeserializeObject<PrerequisiteJson>(this.viewModel.Prerequisite);
                foreach (var keyValue in prerequisiteJson.trainPositions)
                {
                    TrainPositionParameter param = new TrainPositionParameter()
                    {
                        DevTrainID = keyValue.DevTrainID,
                        DevAreaID = keyValue.DevAreaID,
                        DevTrainName = keyValue.DevTrainName,
                        DevAreaName = keyValue.DevAreaName,
                        IsStop = keyValue.IsStop
                    };
                    this.TrainPositionList.Add(param);
                }
                foreach (var keyValue in prerequisiteJson.beforeSteps)
                {
                    BeforeStepParameter param = new BeforeStepParameter()
                    {
                       StepID = keyValue.StepID,
                            Delay = keyValue.Delay,
                    };
                    this.BeforeList.Add(param);
                }

                foreach (var keyValue in prerequisiteJson.parameters)
                {
                    PublicParameter param = new PublicParameter()
                    {
                        DevType = keyValue.DevType,
                        DevID = keyValue.DevID,
                        DevStateID = keyValue.DevStateID,
                        DevName = keyValue.DevName,
                        DevStateName = keyValue.DevStateName,
                    };
                    this.DevStateList.Add(param);
                }
                foreach (var keyValue in prerequisiteJson.intervalMonitors)
                {
                    IntervalMonitorParameter param = new IntervalMonitorParameter()
                    {
                        StartStationID = keyValue.StartStationID,
                        EndStationID = keyValue.EndStationID,
                        Direction = keyValue.Direction,
                        StartStationName = keyValue.StartStationName,
                        EndStationName = keyValue.EndStationName,
                        IsTrainON = keyValue.IsTrainON
                    };
                    this.IntervalMonitorList.Add(param);
                }
            }
            #endregion
            var devTypes = Device_TypeDAL.GetDeviceType();
            //devTypes.Insert(0, new Device_TypeModel() { Id = 0, DeviceType = "未选择" });
            this.DicDevType = devTypes.ToDictionary(t => t.Id, t => t.DeviceType);
            this.DicDevType1 = devTypes.ToDictionary(t => t.Id, t => t.DeviceType);
            this.cmbTaskStepItem.ItemsSource = StepItemList;
            this.cmbStepIDItem.ItemsSource = StepItemList;

            this.cmbSystemType.ItemsSource = Enum.GetValues(typeof(SystemType))
                .Cast<SystemType>().ToDictionary(t => (int)t, t => t.ToString());

            this.cmbTaskType.ItemsSource = Enum.GetValues(typeof(TaskType))
                .Cast<TaskType>().ToDictionary(t => (int)t, t => t.ToString());
            if(viewModel.DeviceTypeId != 0)
            {
                var deviceList = MainWindowNew.DeviceList[viewModel.DeviceTypeId];
                var deviceIdList = viewModel.DeviceId.Split(',').ToList();
                var temp = deviceList.Where(x => deviceIdList.Contains(x.DeviceId.ToString())).ToList();
                this.cmbDevice.SelectedItems.Clear();
                foreach (var device in temp)
                {
                    this.cmbDevice.SelectedItems.Add(device);
                }
            }
            
            //Dictionary<int, string> ScoreStandards = Enum.GetValues(typeof(ScoreStandard))
            //    .Cast<ScoreStandard>().ToDictionary(t => (int)t, t => t.ToString());
            //this.cmbScoreStandard.ItemsSource = ScoreStandards;

            //List<TestQuestionTaskStepViewModel> StepList = new List<TestQuestionTaskStepViewModel>();
            //StepList.AddRange(TestPaper.TestQuestionTaskStepList.FindAll(s => s.TaskType == (int)TaskType.作业 && s.TestQuestionTaskStepID != viewModel.TestQuestionTaskStepID));
            //this.cmbMutexStep.ItemsSource = TestPaper.TestQuestionTaskStepList;
            //zzg无此字段
            //if (viewModel.Model.MutexStep !=""|| viewModel.Model.MutexStep != "NULL")
            //{
            //    this.cmbMutexStep.SelectedValue = viewModel.Model.MutexStep;
            //}


            this.DataContext = this;

            if (this.IsLook)
                TestQuestionEdit.JudgeIsLook(this.LayOut);
            MyDirection.Add(new DirectionClass() {DeviceID=1,DevName="上行"} );
            MyDirection.Add(new DirectionClass() { DeviceID = 2, DevName = "下行" });
            select = Task.Run(() =>
            {
                while (true)
                {
                    if (tokenSource.IsCancellationRequested)
                    {
                        break;
                    }
                    while (IsSelected)
                    {
                        try
                        {
                            this.Dispatcher.Invoke(new Action(() =>
                            {
                                if (this.stepKeyText.Text == "")
                                {
                                    //this.cmbMutexStep.ItemsSource = TestPaper.TestQuestionTaskStepList;
                                }
                                else
                                {
                                    fuzzyQuery.KeyText = this.stepKeyText.Text;
                                    //this.cmbMutexStep.ItemsSource = tempStepList;
                                }
                            }));
                        }
                        catch (Exception ex)
                        {

                        }
                        Thread.Sleep(1000);

                    }
                }

            }, cancellationToken);
        }
        private void UpdateQueryResult(string KeyText)//模糊搜索筛选互斥步骤方法 Add by gy
        {
            tempStepList = TestPaper.TestQuestionTaskStepList.Where(o => o.AllDescribe.StartsWith(KeyText)|| o.AllDescribe.EndsWith(KeyText)||o.AllDescribe.IndexOf(KeyText)!=-1).ToList();
        }
        private void BtnPre_Click(object sender, RoutedEventArgs e)
        {
            Button btn = e.OriginalSource as Button;
            switch (btn.Content.ToString())
            {
                case "新建":
                    this.DevStateList.Add(new PublicParameter());
                    break;
                case "删除":
                    var para = dgDevState.SelectedItem as PublicParameter;
                    if (para != null)
                    {
                        this.DevStateList.Remove(para);
                    }
                    break;
            }
        }

        private void BtnPosition_Click(object sender, RoutedEventArgs e)
        {
            Button btn = e.OriginalSource as Button;
            switch (btn.Content.ToString())
            {
                case "新建":
                    this.TrainPositionList.Add(new TrainPositionParameter());
                    break;
                case "删除":
                    var para = dgTrainPosition.SelectedItem as TrainPositionParameter;
                    if (para != null)
                    {
                        this.TrainPositionList.Remove(para);
                    }
                    break;
            }
        }

        private void BtnBefore_Click(object sender, RoutedEventArgs e)
        {
            Button btn = e.OriginalSource as Button;
            switch (btn.Content.ToString())
            {
                case "新建":
                    this.BeforeList.Add(new BeforeStepParameter());
                    break;
                case "删除":
                    var para = dgBeforeStep.SelectedItem as BeforeStepParameter;
                    if (para != null)
                    {
                        this.BeforeList.Remove(para);
                    }
                    break;
            }
        }
        private void BtnInterval_Click(object sender, RoutedEventArgs e)
        {
            Button btn = e.OriginalSource as Button;
            switch (btn.Content.ToString())
            {
                case "新建":
                    this.IntervalMonitorList.Add(new IntervalMonitorParameter());
                    break;
                case "删除":
                    var para = dgIntervalMonitor.SelectedItem as IntervalMonitorParameter;
                    if (para != null)
                    {
                        this.IntervalMonitorList.Remove(para);
                    }
                    break;
            }
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox combox = sender as ComboBox;
            ContentPresenter cp = (sender as ComboBox).TemplatedParent as ContentPresenter;

            if (cp != null)
            {
                if (combox.Name == "cmbDevTrain")//车次
                {
                    TrainPositionParameter parameter = cp.Content as TrainPositionParameter;
                    var dev = combox.SelectedItem as DeviceModel;
                    parameter.DevTrainID = dev.DeviceId;
                    parameter.DevTrainName = dev.DeviceName;
                }
                else if (combox.Name == "cmbArea")//逻辑区段
                {
                    TrainPositionParameter parameter = cp.Content as TrainPositionParameter;
                    var dev = combox.SelectedItem as DeviceModel;
                    parameter.DevAreaName = dev.DeviceName;
                    parameter.DevAreaID= dev.DeviceId;

                }
                else if (combox.Name == "CmbDevTrainOfStation")//所属车站
                {
                    TrainPositionParameter parameter = cp.Content as TrainPositionParameter;
                    MyAreaList = AreaList;
                    DeviceModel selectedItem = (DeviceModel)combox.SelectedItem;
                    var area = AreaList.Where((T => T.DeviceName.Contains(selectedItem.DeviceName.ToString()))).ToList();//修改区段获取方式 modify by gy                    
                    MyAreaList = area;
                    parameter.StationName = selectedItem.DeviceName;
                    parameter.StationID = selectedItem.DeviceId;
                }
                else if (combox.Name == "cmbDevType")//设备类型
                {
                    PublicParameter parameter = cp.Content as PublicParameter;
                    parameter.DevID = 0;
                    parameter.DevName = "";
                    parameter.DevStateID = 0;
                    parameter.DevStateName = "";

                    KeyValuePair<int, string> devType = (KeyValuePair<int, string>)combox.SelectedItem;
                    if (MainWindowNew.DeviceList.ContainsKey(devType.Key))
                    {
                        parameter.DeviceList = MainWindowNew.DeviceList[devType.Key];
                        parameter.DevType = devType.Key;
                    }
                    else
                    {
                        parameter.DeviceList = null;
                    }

                    if (MainWindowNew.DeviceStateList.ContainsKey(devType.Key))
                    {
                        parameter.DeviceStateList = MainWindowNew.DeviceStateList[devType.Key];
                        parameter.DevType = devType.Key;
                    }
                    else
                    {
                        parameter.DeviceStateList = null;
                    }
                }
                else if (combox.Name == "cmbDevName")
                {
                    if (combox.SelectedItem != null)
                    {
                        PublicParameter parameter = cp.Content as PublicParameter;
                        var dev = combox.SelectedItem as DeviceModel;
                        parameter.DevName = dev.DeviceName;
                    }
                }
                else if (combox.Name == "cmbDevStateName")
                {
                    if (combox.SelectedItem != null)
                    {
                        PublicParameter parameter = cp.Content as PublicParameter;
                        var dev = combox.SelectedItem as Device_StateModel;
                        parameter.DevStateName = dev.DeviceStatus;
                    }
                }
              
                else if(combox.Name == "cmbStartStation")
                {
                    IntervalMonitorParameter parameter = cp.Content as IntervalMonitorParameter;
                    var dev = combox.SelectedItem as DeviceModel;
                    parameter.StartStationName = dev.DeviceName;
                }
                else if (combox.Name == "cmbEndStation")
                {
                    IntervalMonitorParameter parameter = cp.Content as IntervalMonitorParameter;
                    var dev = combox.SelectedItem as DeviceModel;
                    parameter.EndStationName = dev.DeviceName;
                }
                else if (combox.Name == "CmbDirection")
                {
                    IntervalMonitorParameter parameter = cp.Content as IntervalMonitorParameter;
                    var dev = combox.SelectedItem as DirectionClass ;
                    parameter.Direction = dev.DevName;
                }

            }
        }

        private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            
            ComboBox combox = sender as ComboBox;
            if (combox.SelectedItem == null) return;
            KeyValuePair<int, string> devType = (KeyValuePair<int, string>)combox.SelectedItem;
            var devs = new List<DeviceModel>();
            if (devType.Key != 0)
                devs.AddRange(MainWindowNew.DeviceList[devType.Key]);
            this.cmbDevice.ItemsSource = devs;
        }



        /// <summary>
        /// 筛选步骤类型 add by gy;
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        
        private void CmbTaskStepItem_DropDownOpened(object sender, EventArgs e)
        {
            if (cmbSystemType.SelectedIndex == 0)
            {
                this.cmbTaskStepItem.ItemsSource = StepItemList;
            }
            else if (cmbSystemType.SelectedIndex == 1)
            {
                this.cmbTaskStepItem.ItemsSource = StepItemList.Where(T => !T.Describes.Contains("信号_"));
            }
            else
            {
                this.cmbTaskStepItem.ItemsSource = StepItemList;
            }
        }
        private void cmbTaskStepItem_KeyUp(object sender, KeyEventArgs e)
        {
            List<OperateItemModel> mylist = new List<OperateItemModel>();
            mylist = StepItemList.FindAll(delegate (OperateItemModel s) { return s.Describes.Contains(cmbTaskStepItem.Text.Trim()); });
            
            this.cmbTaskStepItem.ItemsSource = StepItemList.Where(T => !T.Describes.Contains(cmbTaskStepItem.Text));
            cmbTaskStepItem.ItemsSource = mylist;
            cmbTaskStepItem.IsDropDownOpen = true;
        }
        //北京科研添加 默认为作业操作 add by ljz 2023/7/6
        private void cmbTaskType_DropDownOpened(object sender, EventArgs e)
        {
            if (cmbTaskStepItem.Text.Contains("调度电话_呼出") || cmbTaskStepItem.Text.Contains("调度电话_接听") ||
                cmbTaskStepItem.Text.Contains("无线电台_呼出") || cmbTaskStepItem.Text.Contains("无线电台_呼出"))
            {
                this.cmbTaskType.Text = "作业";
            }

        }
        private void stepKeyText_GotFocus(object sender, RoutedEventArgs e)
        {
            this.IsSelected = true;
        }

        private void stepKeyText_LostFocus(object sender, RoutedEventArgs e)
        {
            this.IsSelected = false;
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            tokenSource.Cancel();//取消筛选的Task
        }

        private void cmbStepIDItem_DropDownOpened(object sender, EventArgs e)
        {
            if (cmbStepIDItem.SelectedIndex == 0)
            {
                this.cmbStepIDItem.ItemsSource = StepItemList;

            }
            else if (cmbStepIDItem.SelectedIndex == 1)
            {
                this.cmbStepIDItem.ItemsSource = StepItemList.Where(T => T.Describes.Contains("信号_"));
            }
            else if (cmbStepIDItem.SelectedIndex == 2)
            {
                this.cmbStepIDItem.ItemsSource = StepItemList.Where(T =>! T.Describes.Contains("信号_"));
            }
            else if (cmbStepIDItem.SelectedIndex == 3)
            {
                this.cmbStepIDItem.ItemsSource = StepItemList.Where(T => !T.Describes.Contains("信号_"));
            }
            
        }

        private void cmbDicDevType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox combox = sender as ComboBox;
            if (combox.SelectedItem == null) return;
            KeyValuePair<int, string> devType = (KeyValuePair<int, string>)combox.SelectedItem;
            var devs = new List<DeviceModel>();
            if (devType.Key != 0)
                devs.AddRange(MainWindowNew.DeviceList[devType.Key]);
            this.cmbDicDevType.ItemsSource = devs;
        }

        private void cbEstimate_Click(object sender, RoutedEventArgs e)
        {
            //if (cbEstimate.IsChecked == true)
            //{
            //    wpEstimate.Visibility = Visibility.Visible;
            //}
            //else
            //{
            //    wpEstimate.Visibility = Visibility.Collapsed;
            //}
        }

        private void cmbDevice_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            List<DeviceModel> deviceList = new List<DeviceModel>();
            
            foreach( var device in e.AddedItems)
            {
                deviceList.Add((DeviceModel)device);
            }
            
            deviceList.Clear();
        }
    }

    public class PublicParameter : NotifyPropertyChanged
    {
        public int ErrorType { get; set; }
        public string CurrentStation { get; set; }
        public int DevType { get; set; }

        private string m_DevTypeName;
        public string DevTypeName
        {
            get { return DevType == 0 ? "" : ((DeviceTypeEnum)DevType).ToString(); }
            set
            {
                this.m_DevTypeName = value;
            }
        }

        private int m_DevID;
        public int DevID
        {
            get
            {
                return this.m_DevID;
            }
            set
            {
                this.m_DevID = value;
                this.OnPropertyChanged();
            }
        }

        private string m_DevName;
        public string DevName
        {
            get
            {
                return this.m_DevName;
            }
            set
            {
                this.m_DevName = value;
                this.OnPropertyChanged();
            }
        }

        private int m_DevStateID;
        public int DevStateID
        {
            get
            {
                return this.m_DevStateID;
            }
            set
            {
                this.m_DevStateID = value;
                this.OnPropertyChanged();
            }
        }

        private string m_DevStateName;
        public string DevStateName
        {
            get
            {
                return this.m_DevStateName;
            }
            set
            {
                this.m_DevStateName = value;
                this.OnPropertyChanged();
            }
        }

        private bool? m_Fault;
        public bool? Fault
        {
            get
            {
                return this.m_Fault;
            }
            set
            {
                this.m_Fault = value;
                this.OnPropertyChanged();
            }
        }
        public int ValueID { get; set; }

        public string Value { get; set; }

        private List<DeviceModel> m_DeviceList;
        public List<DeviceModel> DeviceList
        {
            get { return this.m_DeviceList; }
            set
            {
                this.m_DeviceList = value;
                this.OnPropertyChanged();
            }
        }

        private List<Device_StateModel> m_DeviceStateList;
        public List<Device_StateModel> DeviceStateList
        {
            get { return this.m_DeviceStateList; }
            set
            {
                this.m_DeviceStateList = value;
                this.OnPropertyChanged();
            }
        }
    }

    public class TrainPositionParameter : NotifyPropertyChanged
    {
        /// <summary>
        /// 车次
        /// </summary>
        private int m_DevTrainID;
        public int DevTrainID
        {
            get
            {
                return this.m_DevTrainID;
            }
            set
            {
                this.m_DevTrainID = value;
                this.OnPropertyChanged();
            }
        }
        /// <summary>
        /// 列车名称
        /// </summary>
        private string m_DevTrainName;
        public string DevTrainName
        {
            get
            {
                return this.m_DevTrainName;
            }
            set
            {
                this.m_DevTrainName = value;
                this.OnPropertyChanged();
            }
        }
        /// <summary>
        /// 车站id
        /// </summary>
        private int m_StationID;
        public int StationID
        {
            get
            {
                return this.m_StationID;
            }
            set
            {
                this.m_StationID = value;
                this.OnPropertyChanged();
            }
        }
        /// <summary>
        /// 车站名称
        /// </summary>
        private string m_StationName;
        public string StationName
        {
            get
            {
                return this.m_StationName;
            }
            set
            {
                this.m_StationName = value;
                this.OnPropertyChanged();
            }
        }
        /// <summary>
        /// 逻辑区段id
        /// </summary>
        private int m_DevAreaID;
        public int DevAreaID
        {
            get
            {
                return this.m_DevAreaID;
            }
            set
            {
                this.m_DevAreaID = value;
                this.OnPropertyChanged();
            }
        }

        /// <summary>
        /// 逻辑区段名称
        /// </summary>
        private string m_DevAreaName;
        public string DevAreaName
        {
            get
            {
                return this.m_DevAreaName;
            }
            set
            {
                this.m_DevAreaName = value;
                this.OnPropertyChanged();
            }
        }

        /// <summary>
        /// 是否停稳
        /// </summary>
        private bool m_IsStop;
        public bool IsStop
        {
            get
            {
                return this.m_IsStop;
            }
            set
            {
                this.m_IsStop = value;
                this.OnPropertyChanged();
            }
        }
        
    }

    public class BeforeStepParameter : NotifyPropertyChanged
    {
        private int m_StepID;
        public int StepID
        {
            get
            {
                return this.m_StepID;
            }
            set
            {
                this.m_StepID = value;
                this.OnPropertyChanged();
            }
        }

        private string m_StepName;
        public string StepName
        {
            get
            {
                return this.m_StepName;
            }
            set
            {
                this.m_StepName = value;
                this.OnPropertyChanged();
            }
        }

        private int m_Delay;
        public int Delay
        {
            get
            {
                return this.m_Delay;
            }
            set
            {
                this.m_Delay = value;
                this.OnPropertyChanged();
            }
        }
    }
    public class IntervalMonitorParameter:NotifyPropertyChanged //区间监测 Add by gy
    {
        private int m_StartStationID;
        public int StartStationID
        {
            get { return this.m_StartStationID; }
            set
            {
                this.m_StartStationID = value;
                this.OnPropertyChanged();
            }
        }
        private string m_StartStationName;
        public string StartStationName
        {
            get
            {
                return this.m_StartStationName;
            }
            set
            {
                this.m_StartStationName = value;
                this.OnPropertyChanged();
            }
        }
        private int m_EndStationID;
        public int EndStationID
        {
            get { return this.m_EndStationID; }
            set
            {
                this.m_EndStationID = value;
                this.OnPropertyChanged();
            }
        }
        private string m_EndStationName;
        public string EndStationName
        {
            get { return this.m_EndStationName; }
            set
            {
                this.m_EndStationName = value;
                this.OnPropertyChanged();
            }
        }
        private string m_Direction;
        public string Direction
        {
            get { return this.m_Direction; }
            set
            {
                this.m_Direction = value;
                this.OnPropertyChanged();
            }
        }
        private bool m_IsTrainON;
        public bool IsTrainON
        {
            get { return this.m_IsTrainON;}
            set
            {
                this.m_IsTrainON = value;
                this.OnPropertyChanged();
            }
        }
    }
    /// <summary>
    /// 前提条件;前提条件：以Json字符串格式保存
    /// </summary>
    public class PrerequisiteJson : NotifyPropertyChanged
    {
        /// <summary>
        /// 列车位置
        /// </summary>
        public List<TrainLocation> trainPositions = new List<TrainLocation>(); 
        /// <summary>
        /// 事前步骤
        /// </summary>
        public List<AdvanceSteps>  beforeSteps = new List<AdvanceSteps>();
        /// <summary>
        /// 设备状态
        /// </summary>
        public List<DeviceStatus> parameters = new List<DeviceStatus>();

        /// <summary>
        /// 区间检测
        /// </summary>
        public List<IntervalDetection> intervalMonitors = new List<IntervalDetection>();

    }
    /// <summary>
    ///列车位置
    /// </summary>
    public class TrainLocation
    {
        /// <summary>
        /// 列车ID
        /// </summary>
        public int DevTrainID { get; set; }

        /// <summary>
        /// 列车名称
        /// </summary>
        public string DevTrainName { get; set; }
        /// <summary>
        /// 车站ID
        /// </summary>
        public int StationID { get; set; }
        /// <summary>
        /// 车站名称
        /// </summary>
        public string StationName { get; set; }
        /// <summary>
        /// 逻辑区段id
        /// </summary>
        public int DevAreaID { get; set; }
        ///逻辑区段名称
        public string DevAreaName { get; set; }
        /// <summary>
        /// 是否停稳
        /// </summary>
        public bool IsStop { get; set; }
    }
    /// <summary>
    /// 事前步骤
    /// </summary>
    public class AdvanceSteps
    {
        /// <summary>
        /// 步骤ID
        /// </summary>
        public int StepID { get; set; }
        /// <summary>
        /// 延时时间
        /// </summary>
        public int Delay { get; set; }
    }
    /// <summary>
    /// 设备状态
    /// </summary>
    public class DeviceStatus
    {
        /// <summary>
        /// 设备类型
        /// </summary>
        public int DevType { get; set; }

        /// <summary>
        /// 设备类型名称
        /// </summary>
        public string DevTypeName { get; set; }

        /// <summary>
        /// 设备ID
        /// </summary>
        public int DevID { get; set; }


        /// <summary>
        /// 设备名称
        /// </summary>
        public string DevName { get; set; }

        /// <summary>
        /// 设备状态ID
        /// </summary>
        public int DevStateID { get; set; }


        /// <summary>
        /// 设备状态名称
        /// </summary>
        public string DevStateName { get; set; }

    }
    /// <summary>
    /// 区间检测
    /// </summary>
    public class IntervalDetection
    {
        /// <summary>
        /// 始站id
        /// </summary>
        public int StartStationID { get; set; }
        /// <summary>
        /// 始站名称
        /// </summary>

        public string StartStationName { get; set; }
        /// <summary>
        /// 终站名称ID
        /// </summary>
        public int EndStationID { get; set; }
        /// <summary>
        /// 终站名称
        /// </summary>
        public string EndStationName { get; set; }
        /// <summary>
        /// 方向
        /// </summary>
        public string Direction { get; set; }
        /// <summary>
        /// 是否有列车
        /// </summary>
        public bool IsTrainON { get; set; }
    }

    public class DirectionClass
    {
       public int DeviceID { get; set; }
       public string DevName { get; set; }
    }
    public class ListenToFuzzyQueryVoid//用于互斥步骤模糊搜索
    {
        
        private string m_keyText = "";
        public string KeyText
        {
            get { return m_keyText; }
            set
            {
                if (value != m_keyText)
                {
                    m_keyText = value;
                    KeyTextChange();
                }

            }
        }
        public delegate void FuzzyQueryEventHandler(string Keytext);
        public event FuzzyQueryEventHandler OnFuzzyQuery;
        //触发事件
        public void KeyTextChange()
        {
            if (OnFuzzyQuery != null)
            {
                OnFuzzyQuery(this.KeyText);
            }
        }
    }
}
